package com.spark.demonetty.netty_demo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;

/**
 * @author fuqiang
 * @Description netty 服务端 抽象父类,抽出公共部分
 * @Date 2020/10/22
 */
public abstract class AbstractServer {

    /**
     * 配置服务端nio线程组
     */
    protected EventLoopGroup bossGroup = new NioEventLoopGroup();
    protected EventLoopGroup workerGroup = new NioEventLoopGroup();

    public void bind(final int port){
        try {
            ServerBootstrap b = getDefaultBootstrap();
            // 绑定端口 同步等待成功
            ChannelFuture sync = b.bind(port).sync();
            // 等待服务端监听端口关闭
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 优雅退出, 释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public void run( int port,final String url,final String ip){
        try {
            ServerBootstrap b = getDefaultBootstrap(url);
            // 绑定端口 同步等待成功
            ChannelFuture sync = b.bind(ip,port).sync();
            System.out.println("服务器启动成功 网址是:" + ip +":"+ port + url);
            // 等待服务端监听端口关闭
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 优雅退出, 释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


    /**
     * 返回启动引导类
     * @return
     */
    public abstract ServerBootstrap getDefaultBootstrap();

    public  ServerBootstrap getDefaultBootstrap(String url){
        return null;
    }
}
